import { ENTRY_PARAMS } from '@/constants/common';
import { useService } from './services';
import Utils from './utils';
import Storage from './storage';

const defaultConfig = {
  debug: false,
  appId: '',
  timestamp: '',
  nonceStr: '',
  signature: '',
  jsApiList: [
    'hideMenuItems',
    'closeWindow',
    'showMenuItems',
    'previewImage',
    'setCloseWindowConfirmDialogInfo'
  ],
  openTagList: ['wx-open-launch-weapp']
};
let inited = false;

export const init = () => {
  const actions = useService();

  // 如果是ios，就只init一次，不重复init
  if (!Utils.browser().android) {
    if (inited) return;
    inited = true;
  }

  let appId = Storage.get(ENTRY_PARAMS)?.appId;

  let [url] = window.location.href.split('#');

  appId &&
    window.setTimeout(function () {
      actions.hos
        .getWxSdk({ url, appId })
        .then((config) => {
          wx.config(Object.assign({}, defaultConfig, config));

          hideShareItem();
        })
        .catch(console);
    }, 800);
};

wx.ready(() => {
  console.log('wx ready');
  hideShareItem();
});

wx.error((res) => {
  console.log(res, 'err');
});

function hideShareItem() {
  wx.hideMenuItems({
    menuList: [
      'menuItem:share:QZone',
      'menuItem:share:weiboApp',
      'menuItem:share:qq',
      'menuItem:share:appMessage',
      'menuItem:share:timeline',
      'menuItem:share:email',
      'menuItem:share:brand',
      'menuItem:share:facebook',

      'menuItem:openWithQQBrowser',
      'menuItem:openWithSafari',
      'menuItem:originPage',
      'menuItem:copyUrl',
      'menuItem:readMode'
    ]
  });
}

export const closeWindow = () => {
  wx.closeWindow();
};
